package com.qsign.sfrz_android.activity.home.ViewController;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.print_sdk.PrintUtil;
import com.google.gson.Gson;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qsign.sfrz_android.R;
import com.qsign.sfrz_android.activity.home.Model.FuheModel;
import com.qsign.sfrz_android.activity.home.Model.PrintContract;
import com.qsign.sfrz_android.base.NewBaseActivity;
import com.qsign.sfrz_android.net.IServiceImpl;
import com.qsign.sfrz_android.net.RequestServiceImpl;
import com.qsign.sfrz_android.publicview.SimpleDialog;
import com.qsign.sfrz_android.utils.BaseUtil;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class FuheActivity extends NewBaseActivity {
    @BindView(R.id.chukuNo)
    TextView chukuNo;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    QuickAdapter quickAdapter;
    List<FuheModel> fuheArray = new ArrayList<FuheModel>();
    PrintContract printContract;
    int pagenumber=0;
    int number=1000000001; // 初始化票据流水号 Initial bill serial number
    private FuheModel thisfuhemodel=null;
    @Override
    protected void initTitle(TextView textView) {
        textView.setText("棉纱入库复核");
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fuhe;
    }

    @Override
    protected void onResume() {
        super.onResume();
        showWait();
        RequestServiceImpl.fh_query(mMIPHandler, IServiceImpl.FH_QUERY,getIntent().getStringExtra("fuhebizno"));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recyclerview.setAdapter(quickAdapter);

        chukuNo.setText("棉纱出库单号："+getIntent().getStringExtra("fuhebizno"));

        PrintUtil pUtil= PrintUtil.getClient ();
        pUtil.setPrintEventListener (new PrintUtil.OnPrintEventListener () {
            @Override
            public void onPrintStatus(int state) {
                Log.e (TAG, "onPrintState: " + state);
                switch (state) {
                    case 0:
                        number+=1; // 流水号自加1 Serial number plus 1
                        pagenumber--;

                        Toast.makeText (FuheActivity.this,"打印成功", Toast.LENGTH_SHORT).show ();
                        break;
                    case 1:
                        Toast.makeText (FuheActivity.this, "没有打印纸了", Toast.LENGTH_SHORT).show ();
                        break;
                    case 2:
                        Toast.makeText (FuheActivity.this, "打印失败", Toast.LENGTH_SHORT).show ();
                        break;

                }
            }
            @Override
            public void onVersion(String version) {
                Log.e (TAG, "onVersion: " + version);
            }
        });

        printContract=new PrintContract(this, pUtil);
        printContract.printInit ();


    }
    public class QuickAdapter extends BaseQuickAdapter<FuheModel, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.fuhe_list_item, fuheArray);
        }

        @Override
        protected BaseViewHolder createBaseViewHolder(View view) {
            AutoUtils.auto(view);
            return super.createBaseViewHolder(view);
        }

        @Override
        protected void convert(BaseViewHolder holder, final FuheModel item) {
            TextView indext= holder.getView(R.id.numberno);
            TextView SZXX= holder.getView(R.id.SZXX);
            TextView DIRECTION= holder.getView(R.id.DIRECTION);
            TextView YARNTYPE= holder.getView(R.id.YARNTYPE);
            TextView ORIPLACE= holder.getView(R.id.ORIPLACE);
            TextView BATCHNO= holder.getView(R.id.BATCHNO);
            TextView YLZL= holder.getView(R.id.YLZL);
            TextView TPZL= holder.getView(R.id.TPZL);
            RelativeLayout itemlay= holder.getView(R.id.itemlay);
            indext.setText(holder.getLayoutPosition()+1+"");
            SZXX.setText(item.getSZXX());
            DIRECTION.setText(item.getDIRECTION());
            YARNTYPE.setText(item.getYARNTYPE());
            ORIPLACE.setText(item.getORIPLACE());
            BATCHNO.setText(item.getBATCHNO());
            TPZL.setText(item.getTPZL());
            try{
                float mm=(float)(Double.parseDouble(item.getYLZL())-Double.parseDouble(item.getYDYZL()));
                YLZL.setText(mm+"/"+item.getYLZL());
            }catch (Exception e){}

            if(item.getYLZL().equals(item.getYDYZL())){
                itemlay.setBackgroundColor(Color.rgb(	255,228,181));
            }else{
                itemlay.setBackgroundColor(Color.rgb(	255,255,255));
            }
            holder.getView(R.id.itemlay).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//打印弹出框
                    thisfuhemodel=item;
                    showWait();
                    RequestServiceImpl.fh_itemclick(mMIPHandler, IServiceImpl.FUHEITEMCLICK,thisfuhemodel.getPKID());
                }
            });

        }
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
        switch (requestType) {
            case IServiceImpl.FH_QUERY://根据条件查询
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                        fuheArray.clear();
                        if (dataarray != null && dataarray.size() > 0) {
                                Gson gson = new Gson();
                                for (Object o : dataarray) {
                                    JSONObject jsonObject1 = (JSONObject) o;
                                    FuheModel qrBean = gson.fromJson(jsonObject1.toJSONString(), FuheModel.class);
                                    fuheArray.add(qrBean);
                                }
                        }
                        quickAdapter.notifyDataSetChanged();
                        quickAdapter.setEmptyView(R.layout.empty, (ViewGroup) recyclerview.getParent());
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("查询出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
                break;
            case IServiceImpl.PRINTNO://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        String TRAYCODE= jsonObject.getString("TRAYCODE");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for(int i=0;i<pagenumber;i++){
                                    printContract.printBarcode (TRAYCODE,number);
                                }
                            }
                        }).start();
                        showWait();
                        RequestServiceImpl.fh_query(mMIPHandler, IServiceImpl.FH_QUERY,getIntent().getStringExtra("fuhebizno"));

                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("打印出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
                break;
            case IServiceImpl.FUHEITEMCLICK://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                      if(Double.parseDouble(thisfuhemodel.getTPZL())>0&&dataarray!=null&&dataarray.size()>0){//大于0
                          Intent intent=new Intent(FuheActivity.this,FuheHistoryActivity.class);
                          Bundle bundel = new Bundle();
                          bundel.putSerializable("FuheModel", thisfuhemodel);
                          intent.putExtras(bundel);
                          intent.putExtra("printshow",false);
                          intent.putExtra("SYZL",jsonObject.getString("SYZL"));
                          startActivity(intent);
                      }else if(Double.parseDouble(thisfuhemodel.getTPZL())==0){
                          double syzl=Double.parseDouble(thisfuhemodel.getYLZL())-Double.parseDouble(thisfuhemodel.getYDYZL());
                          if(syzl==Double.parseDouble(thisfuhemodel.getYLZL())||dataarray==null||dataarray.size()==0){
                              showPrintDialog();
                          }else if(syzl<Double.parseDouble(thisfuhemodel.getYLZL())){
                              Intent intent=new Intent(FuheActivity.this,FuheHistoryActivity.class);
                              Bundle bundel = new Bundle();
                              bundel.putSerializable("FuheModel", thisfuhemodel);
                              intent.putExtras(bundel);
                              intent.putExtra("printshow",true);
                              intent.putExtra("SYZL",jsonObject.getString("SYZL"));
                              startActivity(intent);
                          }
                      }

                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("打印出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }


                break;

        }
    }
    private void showPrintDialog(){
        View viewTips = LayoutInflater.from(FuheActivity.this).inflate(R.layout.print_dialog, null);
        AutoUtils.auto(viewTips);
        Dialog alertDialog = BaseUtil.ShowMYDialog(FuheActivity.this, viewTips, 340);
        alertDialog.show();
        TextView yuanliaotext = viewTips.findViewById(R.id.yuanliaotext);
        TextView changditext = viewTips.findViewById(R.id.changditext);
        TextView pihaotext = viewTips.findViewById(R.id.pihaotext);
        TextView ylzltext = viewTips.findViewById(R.id.ylzltext);
        TextView haveprinttext = viewTips.findViewById(R.id.haveprinttext);
        EditText numberedit = viewTips.findViewById(R.id.numberedit);
        EditText tuopanedit = viewTips.findViewById(R.id.tuopanedit);
        yuanliaotext.setText(thisfuhemodel.getSZXX());
        changditext.setText(thisfuhemodel.getORIPLACE());
        pihaotext.setText(thisfuhemodel.getBATCHNO());
        ylzltext.setText(thisfuhemodel.getYLZL());
        haveprinttext.setText(TextUtils.isEmpty(thisfuhemodel.getYDYZL())?"":thisfuhemodel.getYDYZL());
        viewTips.findViewById(R.id.printbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                closeKeyboard();
                if(tuopanedit.getEditableText().toString().length()==0){
                    BaseUtil.ShowToast(FuheActivity.this,"请输入托盘重量");
                }else if(numberedit.getEditableText().toString().length()==0){
                    BaseUtil.ShowToast(FuheActivity.this,"请输入打印数量");
                }else if(Double.valueOf(tuopanedit.getEditableText().toString())>Double.valueOf(thisfuhemodel.getYLZL())){
                    BaseUtil.ShowToast(FuheActivity.this,"托盘重量不能大于总重量");
                }else if(!TextUtils.isEmpty(thisfuhemodel.getYDYZL())){
                    double mm=  Double.valueOf(thisfuhemodel.getYLZL())- Double.valueOf(thisfuhemodel.getYDYZL());
                    if(Double.valueOf(tuopanedit.getEditableText().toString())>mm){
                        BaseUtil.ShowToast(FuheActivity.this,"托盘重量不能大于剩余重量");
                    }else{
                        pagenumber=Integer.parseInt(numberedit.getEditableText().toString());
                        showWait();
                        RequestServiceImpl.print(mMIPHandler, IServiceImpl.PRINTNO,thisfuhemodel.getPKID(),tuopanedit.getEditableText().toString());
                    }
                } else{
                    pagenumber=Integer.parseInt(numberedit.getEditableText().toString());
                    showWait();
                    RequestServiceImpl.print(mMIPHandler, IServiceImpl.PRINTNO,thisfuhemodel.getPKID(),tuopanedit.getEditableText().toString());
                }

            }
        });
        viewTips.findViewById(R.id.cancellay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                closeKeyboard();
            }
        });
        numberedit.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showKeyboard(numberedit);
                } else {
                    closeKeyboard();
                }
            }
        });
        tuopanedit.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showKeyboard(tuopanedit);
                } else {
                    closeKeyboard();
                }
            }
        });
        tuopanedit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null) {
                    return;
                }
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                int index = tuopanedit.getSelectionStart();
                if (posDot >= 0 && temp.length() - 3 > posDot) {
                    s.delete(index - 1, index);
                }
            }
        });
    }
    private void showSimpleDialog(String message) {
        SimpleDialog.show(this, message);
    }
    @OnClick(R.id.backbtn)
    public void onViewClicked() {
        finish();
    }
}
